<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-50 via-white to-indigo-50">
    <!-- 顶部导航 -->
    <div class="bg-white shadow-sm border-b border-gray-200 sticky top-0 z-10">
      <div class="max-w-7xl mx-auto px-3 sm:px-6 lg:px-8 py-3 sm:py-4">
        <div class="flex items-center justify-between gap-2">
          <!-- 左侧：返回按钮和标题 -->
          <div class="flex items-center gap-2 sm:gap-4 min-w-0 flex-1">
            <button
              @click="goBack"
              class="p-2 hover:bg-gray-100 rounded-lg transition-colors flex-shrink-0"
            >
              <ArrowLeft class="w-5 h-5 text-gray-600" />
            </button>
            <div class="min-w-0 flex-1">
              <h1 class="text-base sm:text-xl font-bold text-gray-900 truncate">批改报告</h1>
              <p class="text-xs sm:text-sm text-gray-500 truncate" v-if="essay">{{ essay.title || '未命名作文' }}</p>
            </div>
          </div>
          
          <!-- 右侧：操作按钮 - 响应式布局 -->
          <div class="flex items-center gap-1 sm:gap-2 flex-shrink-0">
            <!-- 移动端：仅图标 -->
            <button
              @click="recheckEssay"
              :disabled="isRechecking"
              class="p-2 sm:px-4 sm:py-2 bg-white border border-gray-300 hover:bg-gray-50 text-gray-700 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed inline-flex items-center gap-2"
              :title="'重新批改'"
            >
              <RotateCw class="w-4 h-4" :class="{ 'animate-spin': isRechecking }" />
              <span class="hidden sm:inline">重新批改</span>
            </button>
            
            <button
              @click="downloadReport"
              class="p-2 sm:px-4 sm:py-2 bg-white border border-gray-300 hover:bg-gray-50 text-gray-700 rounded-lg transition-colors inline-flex items-center gap-2"
              title="保存报告"
            >
              <Download class="w-4 h-4" />
              <span class="hidden sm:inline">保存报告</span>
            </button>
            
            <button
              @click="shareReport"
              class="p-2 sm:px-4 sm:py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-colors inline-flex items-center gap-2"
              title="分享"
            >
              <Share2 class="w-4 h-4" />
              <span class="hidden sm:inline">分享</span>
            </button>
          </div>
        </div>
      </div>
    </div>

    <div class="max-w-7xl mx-auto px-3 sm:px-4 md:px-6 lg:px-8 py-4 sm:py-8">
      <!-- 加载状态 -->
      <div v-if="loading" class="flex items-center justify-center py-12 sm:py-20">
        <div class="text-center">
          <Loader class="w-10 h-10 sm:w-12 sm:h-12 text-blue-500 animate-spin mx-auto mb-4" />
          <p class="text-sm sm:text-base text-gray-600">正在加载批改结果...</p>
        </div>
      </div>
      
      <!-- 错误状态 -->
      <div v-else-if="error" class="text-center py-12 sm:py-20 px-4">
        <AlertCircle class="w-12 h-12 sm:w-16 sm:h-16 text-red-500 mx-auto mb-4" />
        <h3 class="text-base sm:text-lg font-medium text-gray-900 mb-2">加载失败</h3>
        <p class="text-sm sm:text-base text-gray-600 mb-4">{{ error }}</p>
        <button
          @click="loadCorrectionResult"
          class="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-colors text-sm sm:text-base"
        >
          重新加载
        </button>
      </div>
      
      <!-- 批改结果内容 -->
      <div v-else-if="correctionResult">
        <!-- 标签页导航 - 移动端优化 -->
        <div class="bg-white rounded-lg shadow-sm mb-4 sm:mb-6">
          <div class="flex border-b border-gray-200 overflow-x-auto">
            <button
              v-for="tab in tabs"
              :key="tab.id"
              @click="activeTab = tab.id"
              class="flex-1 min-w-[80px] px-3 sm:px-6 py-3 sm:py-4 text-center font-medium transition-colors relative whitespace-nowrap"
              :class="[
                activeTab === tab.id
                  ? 'text-blue-600 bg-blue-50'
                  : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
              ]"
            >
              <div class="flex flex-col sm:flex-row items-center justify-center gap-1 sm:gap-2">
                <component :is="tab.icon" class="w-4 h-4 sm:w-5 sm:h-5" />
                <span class="text-xs sm:text-base">{{ tab.label }}</span>
              </div>
              <!-- 激活指示器 -->
              <div
                v-if="activeTab === tab.id"
                class="absolute bottom-0 left-0 right-0 h-0.5 bg-blue-600"
              ></div>
            </button>
          </div>
        </div>
        
        <!-- 标签页内容 -->
        <div class="transition-all duration-300">
          <!-- 标签1: 总览 -->
          <div v-show="activeTab === 'overview'" class="space-y-6">
            <!-- 评分区域 -->
            <ScoreDisplay 
              :score-breakdown="correctionResult.score_breakdown"
              :animated="true"
            />
            
            <!-- 总评卡片 - 移动端优化 -->
            <div class="bg-white rounded-lg shadow-sm p-4 sm:p-6">
              <h3 class="text-base sm:text-lg font-medium text-gray-900 mb-3 sm:mb-4">总体评价</h3>
              <div class="prose prose-sm max-w-none text-gray-700">
                <p class="text-sm sm:text-base leading-relaxed">{{ getOverallComment() }}</p>
              </div>
            </div>
            
            <!-- 数据概要 - 移动端优化 -->
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 sm:gap-4">
              <div class="bg-white rounded-lg shadow-sm p-4 sm:p-6">
                <div class="flex items-center gap-2 sm:gap-3">
                  <div class="w-8 h-8 sm:w-10 sm:h-10 bg-red-100 rounded-lg flex items-center justify-center flex-shrink-0">
                    <AlertCircle class="w-4 h-4 sm:w-6 sm:h-6 text-red-600" />
                  </div>
                  <div>
                    <div class="text-xl sm:text-2xl font-bold text-gray-900">
                      {{ correctionResult.error_count || 0 }}
                    </div>
                    <div class="text-xs sm:text-sm text-gray-500">发现问题</div>
                  </div>
                </div>
              </div>
              
              <div class="bg-white rounded-lg shadow-sm p-4 sm:p-6">
                <div class="flex items-center gap-2 sm:gap-3">
                  <div class="w-8 h-8 sm:w-10 sm:h-10 bg-green-100 rounded-lg flex items-center justify-center flex-shrink-0">
                    <Sparkles class="w-4 h-4 sm:w-6 sm:h-6 text-green-600" />
                  </div>
                  <div>
                    <div class="text-xl sm:text-2xl font-bold text-gray-900">
                      {{ getHighlightCount() }}
                    </div>
                    <div class="text-xs sm:text-sm text-gray-500">标记亮点</div>
                  </div>
                </div>
              </div>
              
              <div class="bg-white rounded-lg shadow-sm p-4 sm:p-6 sm:col-span-2 lg:col-span-1">
                <div class="flex items-center gap-2 sm:gap-3">
                  <div class="w-8 h-8 sm:w-10 sm:h-10 bg-blue-100 rounded-lg flex items-center justify-center flex-shrink-0">
                    <FileText class="w-4 h-4 sm:w-6 sm:h-6 text-blue-600" />
                  </div>
                  <div>
                    <div class="text-xl sm:text-2xl font-bold text-gray-900">
                      {{ essay?.content?.length || 0 }}
                    </div>
                    <div class="text-xs sm:text-sm text-gray-500">字数统计</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 标签2: 精批详情 - 移动端优化 -->
          <div v-show="activeTab === 'details'" class="space-y-4">
            <!-- 颜色图例说明 -->
            <div class="bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg p-3 sm:p-4 border border-blue-200">
              <div class="flex items-center gap-2 mb-2">
                <Sparkles class="w-4 h-4 text-blue-600" />
                <span class="text-sm font-medium text-gray-800">批注颜色说明</span>
              </div>
              <div class="flex flex-wrap gap-2 sm:gap-3 text-xs">
                <div class="flex items-center gap-1.5">
                  <div class="w-3 h-3 rounded border-2 border-red-500 bg-red-50"></div>
                  <span class="text-gray-700">语言问题</span>
                </div>
                <div class="flex items-center gap-1.5">
                  <div class="w-3 h-3 rounded border-2 border-amber-500 bg-amber-50"></div>
                  <span class="text-gray-700">结构问题</span>
                </div>
                <div class="flex items-center gap-1.5">
                  <div class="w-3 h-3 rounded border-2 border-purple-500 bg-purple-50"></div>
                  <span class="text-gray-700">逻辑问题</span>
                </div>
                <div class="flex items-center gap-1.5">
                  <div class="w-3 h-3 rounded border-2 border-blue-500 bg-blue-50"></div>
                  <span class="text-gray-700">内容问题</span>
                </div>
                <div class="flex items-center gap-1.5">
                  <div class="w-3 h-3 rounded border-2 border-green-500 bg-green-50"></div>
                  <span class="text-gray-700">亮点标注</span>
                </div>
              </div>
            </div>
            
            <!-- 精批详情双栏布局 -->
            <div class="bg-white rounded-lg shadow-sm overflow-hidden">
              <div class="grid grid-cols-1 lg:grid-cols-2 divide-y lg:divide-y-0 lg:divide-x divide-gray-200">
                <!-- 左侧：原文展示（带行内标注） -->
                <div class="p-4 sm:p-6 overflow-y-auto" style="max-height: 600px;">
                  <h3 class="text-base sm:text-lg font-medium text-gray-900 mb-3 sm:mb-4 sticky top-0 bg-white pb-2 flex items-center gap-2">
                    <Eye class="w-5 h-5 text-blue-600" />
                    原文（点击标注查看详情）
                  </h3>
                  <div class="prose prose-sm max-w-none">
                    <div 
                      v-html="highlightedContent"
                      class="whitespace-pre-wrap leading-relaxed text-gray-700 text-sm sm:text-base"
                    ></div>
                  </div>
                </div>
                
                <!-- 右侧：批注列表 -->
                <div class="p-4 sm:p-6 overflow-y-auto bg-gray-50" style="max-height: 600px;">
                  <h3 class="text-base sm:text-lg font-medium text-gray-900 mb-3 sm:mb-4 sticky top-0 bg-gray-50 pb-2 flex items-center gap-2">
                    <AlertCircle class="w-5 h-5 text-orange-600" />
                    详细批注
                  </h3>
                  <ErrorList 
                    :errors="correctionResult.corrections || []"
                    @error-click="scrollToError"
                  />
                </div>
              </div>
            </div>
          </div>
          
          <!-- 标签3: 修改建议 -->
          <div v-show="activeTab === 'suggestions'">
            <SuggestionPanel 
              :suggestions="getSuggestions()"
              :summary="getSuggestionsSummary()"
            />
          </div>
          
          <!-- 标签4: AI范文 - 移动端优化 -->
          <div v-show="activeTab === 'model'" class="bg-white rounded-lg shadow-sm p-4 sm:p-6">
            <h3 class="text-base sm:text-lg font-medium text-gray-900 mb-3 sm:mb-4">AI范文参考</h3>
            
            <div v-if="correctionResult.model_essay" class="space-y-3 sm:space-y-4">
              <div class="bg-gray-50 rounded-lg p-4 sm:p-6 border border-gray-200">
                <div class="prose prose-sm max-w-none text-gray-700 whitespace-pre-wrap leading-relaxed text-sm sm:text-base">
                  {{ correctionResult.model_essay }}
                </div>
              </div>
              
              <div class="flex items-center justify-center">
                <button
                  @click="compareEssays"
                  class="inline-flex items-center gap-2 px-4 sm:px-6 py-2 sm:py-3 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-colors text-sm sm:text-base"
                >
                  <GitCompare class="w-4 h-4 sm:w-5 sm:h-5" />
                  <span>对比我的作文</span>
                </button>
              </div>
            </div>
            
            <div v-else class="text-center py-8 sm:py-12">
              <FileText class="w-12 h-12 sm:w-16 sm:h-16 text-gray-400 mx-auto mb-3 sm:mb-4" />
              <p class="text-sm sm:text-base text-gray-600">AI范文生成中...</p>
              <p class="text-xs sm:text-sm text-gray-500 mt-2">范文将在批改完成后自动生成</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { 
  ArrowLeft, 
  RotateCw, 
  Download, 
  Share2, 
  Loader, 
  AlertCircle,
  Eye,
  FileText,
  Lightbulb,
  BookOpen,
  Sparkles,
  GitCompare
} from 'lucide-vue-next';
import { useCorrectionStore } from '../stores/correction.js';
import { useEssayStore } from '../stores/essay.js';
import { getCorrectionErrorMessage } from '../utils/correctionErrors.js';
import ScoreDisplay from '../components/ScoreDisplay.vue';
import ErrorList from '../components/ErrorList.vue';
import SuggestionPanel from '../components/SuggestionPanel.vue';

/**
 * CorrectionResultPage 组件
 * 批改结果详情页，包含4个标签页：总览、精批详情、修改建议、AI范文
 */

// ==================== Composition API ====================
const route = useRoute();
const router = useRouter();
const correctionStore = useCorrectionStore();
const essayStore = useEssayStore();

// ==================== Refs ====================
const activeTab = ref('overview');
const loading = ref(true);
const error = ref(null);
const errorDetail = ref(null);  // 详细错误信息
const isRechecking = ref(false);
const pollingInterval = ref(null);  // 轮询定时器
const pollingAttempts = ref(0);  // 轮询尝试次数
const maxPollingAttempts = 30;  // 最大轮询次数（60秒）

// ==================== Computed ====================

/**
 * 批改结果数据
 */
const correctionResult = computed(() => correctionStore.correctionResult);

/**
 * 作文数据
 */
const essay = computed(() => {
  const essayId = route.params.essayId;
  return essayStore.essays.find(e => e.id === essayId);
});

/**
 * 标签页配置
 */
const tabs = computed(() => [
  { id: 'overview', label: '总览', icon: Eye },
  { id: 'details', label: '精批详情', icon: FileText },
  { id: 'suggestions', label: '修改建议', icon: Lightbulb },
  { id: 'model', label: 'AI范文', icon: BookOpen },
]);

/**
 * 清洗作文内容 - 移除系统调试信息
 */
const cleanContent = (rawContent) => {
  if (!rawContent) return '';
  
  // 移除mcp-feedback-enhanced等系统调试信息
  let cleaned = rawContent;
  
  // 移除JSON格式的调试信息 (如：{"status": "...", "current_step": "..."})
  cleaned = cleaned.replace(/\{[^}]*"status"[^}]*"tool_used"[^}]*"message"[^}]*\}/g, '');
  cleaned = cleaned.replace(/\{[^}]*"current_step"[^}]*"next_step"[^}]*\}/g, '');
  cleaned = cleaned.replace(/mcp-feedback-enhanced/g, '');
  
  // 移除多余的空白行
  cleaned = cleaned.replace(/\n{3,}/g, '\n\n');
  
  return cleaned.trim();
};

/**
 * 高亮后的内容（带行内标注）
 */
const highlightedContent = computed(() => {
  if (!essay.value?.content) return '';
  
  let content = cleanContent(essay.value.content);
  const corrections = correctionResult.value?.corrections || [];
  
  // 按位置排序，从后往前替换（避免位置偏移）
  const sortedCorrections = [...corrections].sort((a, b) => {
    // 简单处理：假设corrections有start和end字段
    // 如果没有，可以尝试通过original文本匹配
    return (b.start || 0) - (a.start || 0);
  });
  
  sortedCorrections.forEach((correction, index) => {
    const { type, original, original_text } = correction;
    const textToHighlight = original || original_text;
    
    if (!textToHighlight) return;
    
    // 根据类型应用不同的颜色样式
    let style = '';
    let bgColor = '';
    
    // 映射错误类型到类别
    const categoryMap = {
      'spelling': 'language',
      'grammar': 'language',
      'punctuation': 'language',
      'word_choice': 'language',
      'sentence_structure': 'structure',
      'paragraph_structure': 'structure',
      'logic': 'logic',
      'coherence': 'logic',
      'content': 'content',
      'theme': 'content',
      'detail': 'detail',
      'highlight': 'highlight',
    };
    
    const category = categoryMap[type] || 'detail';
    
    // 根据类别应用不同的颜色标记
    if (category === 'language') {
      style = 'border-b-2 border-red-500 bg-red-50/50 rounded px-1 cursor-pointer hover:bg-red-100 transition-colors';
      bgColor = 'text-red-700';
    } else if (category === 'structure') {
      style = 'border-b-2 border-amber-500 bg-amber-50/50 rounded px-1 cursor-pointer hover:bg-amber-100 transition-colors';
      bgColor = 'text-amber-700';
    } else if (category === 'logic') {
      style = 'border-b-2 border-purple-500 bg-purple-50/50 rounded px-1 cursor-pointer hover:bg-purple-100 transition-colors';
      bgColor = 'text-purple-700';
    } else if (category === 'content') {
      style = 'border-b-2 border-blue-500 bg-blue-50/50 rounded px-1 cursor-pointer hover:bg-blue-100 transition-colors';
      bgColor = 'text-blue-700';
    } else if (category === 'highlight') {
      style = 'border-b-2 border-green-500 bg-green-50/50 rounded px-1 cursor-pointer hover:bg-green-100 transition-colors';
      bgColor = 'text-green-700';
    } else {
      style = 'border-b-2 border-gray-500 bg-gray-50/50 rounded px-1 cursor-pointer hover:bg-gray-100 transition-colors';
      bgColor = 'text-gray-700';
    }
    
    // 替换原文为带样式的span，添加序号标记
    const highlightedText = `<span class="${style} ${bgColor} font-medium relative inline-block" data-correction="${escape(JSON.stringify(correction))}" data-index="${index + 1}" title="点击查看详情">${textToHighlight}<sup class="ml-0.5 text-xs">${index + 1}</sup></span>`;
    
    // 使用正则表达式进行全局替换（只替换第一个匹配项）
    const escapedText = textToHighlight.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    content = content.replace(new RegExp(escapedText), highlightedText);
  });
  
  return content;
});

// ==================== Methods ====================

/**
 * 获取总体评语
 */
const getOverallComment = () => {
  const result = correctionResult.value;
  
  // 根据学段返回不同字段的评语
  if (result.encouraging_comments) {
    return result.encouraging_comments; // 小学
  } else if (result.strength_analysis && result.weakness_analysis) {
    return `${result.strength_analysis} ${result.weakness_analysis}`; // 初中
  } else if (result.depth_analysis) {
    return result.depth_analysis; // 高中
  }
  
  return '整体表现良好，继续保持！';
};

/**
 * 获取亮点数量
 */
const getHighlightCount = () => {
  const corrections = correctionResult.value?.corrections || [];
  return corrections.filter(c => c.type === 'highlight').length;
};

/**
 * 获取建议列表
 */
const getSuggestions = () => {
  const result = correctionResult.value;
  const suggestions = [];
  
  // 根据学段提取建议
  if (result.improvement_suggestions) {
    // 小学
    result.improvement_suggestions.forEach((s, index) => {
      suggestions.push({
        title: `建议 ${index + 1}`,
        content: typeof s === 'string' ? s : s.content,
        priority: 'medium',
      });
    });
  } else if (result.specific_suggestions) {
    // 初中
    result.specific_suggestions.forEach((s, index) => {
      suggestions.push({
        title: s.title || `建议 ${index + 1}`,
        content: typeof s === 'string' ? s : s.content,
        priority: s.priority || 'medium',
        example: s.example,
      });
    });
  } else if (result.college_prep_suggestions) {
    // 高中
    result.college_prep_suggestions.forEach((s, index) => {
      suggestions.push({
        title: s.title || `建议 ${index + 1}`,
        content: typeof s === 'string' ? s : s.content,
        priority: 'high',
      });
    });
  }
  
  return suggestions;
};

/**
 * 获取建议总结
 */
const getSuggestionsSummary = () => {
  const result = correctionResult.value;
  
  if (result.weakness_analysis) {
    return result.weakness_analysis;
  }
  
  return '继续加强练习，注重细节优化。';
};

/**
 * 清除轮询定时器
 */
const clearPolling = () => {
  if (pollingInterval.value) {
    clearInterval(pollingInterval.value);
    pollingInterval.value = null;
  }
  pollingAttempts.value = 0;
};

/**
 * 加载批改结果（带轮询支持）
 */
const loadCorrectionResult = async (enablePolling = true) => {
  loading.value = true;
  error.value = null;
  errorDetail.value = null;
  
  // 清除之前的轮询
  clearPolling();
  
  try {
    const essayId = route.params.essayId;
    
    // 检查是否是新提交的批改（通过路由query参数）
    const isFreshSubmission = route.query?.fresh === 'true';
    
    console.log('[CorrectionResultPage] Loading result:', { essayId, isFreshSubmission, enablePolling });
    
    // 加载作文数据（如果还没有）
    if (!essay.value) {
      await essayStore.getEssayById(essayId);
    }
    
    // 加载批改结果
    const result = await correctionStore.getCorrectionResult(essayId);
    
    // 检查批改状态
    if (result.data?.status === 'processing') {
      // 如果正在批改中，启动轮询
      if (enablePolling && pollingAttempts.value < maxPollingAttempts) {
        console.log('[CorrectionResultPage] Correction in progress, starting polling...');
        startPolling(essayId);
      } else {
        throw new Error('批改进行中，请稍候...');
      }
    }
    
  } catch (err) {
    console.error('[CorrectionResultPage] Load failed:', err);
    
    // 使用错误处理工具解析错误
    const errorInfo = getCorrectionErrorMessage(err);
    error.value = errorInfo.message || '加载批改结果失败';
    errorDetail.value = errorInfo;
    
    // 对于某些错误类型，尝试轮询
    if (enablePolling && errorInfo.type === 'CORRECTION_IN_PROGRESS' && pollingAttempts.value < maxPollingAttempts) {
      console.log('[CorrectionResultPage] Starting polling due to processing state...');
      startPolling(route.params.essayId);
    }
  } finally {
    loading.value = false;
  }
};

/**
 * 启动轮询机制
 */
const startPolling = (essayId) => {
  // 确保只有一个轮询在运行
  clearPolling();
  
  console.log('[CorrectionResultPage] Starting polling for essay:', essayId);
  
  pollingInterval.value = setInterval(async () => {
    pollingAttempts.value++;
    console.log(`[CorrectionResultPage] Polling attempt ${pollingAttempts.value}/${maxPollingAttempts}`);
    
    try {
      // 不显示loading，静默轮询
      const result = await correctionStore.getCorrectionResult(essayId, false);
      
      // 如果批改完成，停止轮询
      if (result.data?.status === 'completed' || result.data?.status === 'failed') {
        console.log('[CorrectionResultPage] Polling completed, status:', result.data.status);
        clearPolling();
        error.value = null;
        errorDetail.value = null;
      }
    } catch (err) {
      console.log('[CorrectionResultPage] Polling error:', err.message);
      
      // 如果超过最大尝试次数，停止轮询
      if (pollingAttempts.value >= maxPollingAttempts) {
        clearPolling();
        const errorInfo = getCorrectionErrorMessage(new Error('批改超时，请稍后查看结果'));
        error.value = errorInfo.message;
        errorDetail.value = errorInfo;
      }
    }
  }, 2000);  // 每2秒轮询一次
};

/**
 * 返回上一页
 * 优先使用浏览器历史记录返回，如果没有历史则返回历史记录页
 */
const goBack = () => {
  // 检查是否有历史记录可以返回
  if (window.history.length > 1 && document.referrer) {
    router.back();
  } else {
    // 如果没有历史记录，返回到历史记录页
    router.push({ name: 'history' });
  }
};

/**
 * 重新批改
 */
const recheckEssay = async () => {
  if (isRechecking.value) return;
  
  isRechecking.value = true;
  error.value = null;
  errorDetail.value = null;
  
  try {
    const essayId = route.params.essayId;
    console.log('[CorrectionResultPage] Re-checking essay:', essayId);
    
    // 提交批改
    await correctionStore.submitForCorrection(essayId);
    
    console.log('[CorrectionResultPage] Re-check submitted, starting polling...');
    
    // 批改提交成功后，启动轮询等待结果
    // 不立即加载结果，而是使用轮询机制
    loading.value = true;
    startPolling(essayId);
    
  } catch (err) {
    console.error('[CorrectionResultPage] Re-check failed:', err);
    const errorInfo = getCorrectionErrorMessage(err);
    error.value = errorInfo.message || '重新批改失败';
    errorDetail.value = errorInfo;
  } finally {
    isRechecking.value = false;
  }
};

/**
 * 下载报告
 */
const downloadReport = () => {
  alert('下载报告功能开发中...');
  // TODO: 实现PDF报告生成和下载
};

/**
 * 分享报告
 */
const shareReport = () => {
  alert('分享功能开发中...');
  // TODO: 实现报告分享（生成分享链接）
};

/**
 * 对比作文
 */
const compareEssays = () => {
  alert('对比功能开发中...');
  // TODO: 实现作文对比视图
};

/**
 * 滚动到错误位置
 */
const scrollToError = (error) => {
  // TODO: 实现滚动到对应错误的功能
  console.log('Scroll to error:', error);
};

// ==================== Lifecycle ====================

onMounted(() => {
  loadCorrectionResult();
});

onBeforeUnmount(() => {
  // 组件卸载时清除轮询
  clearPolling();
});
</script>

<style scoped>
/* 确保过渡动画流畅 */
.transition-all {
  transition: opacity 0.3s ease-in-out, transform 0.3s ease-in-out;
}

/* prose样式增强 */
.prose {
  max-width: none;
}
</style>

